const { login } = require('../controller/user')
const { SuccessModel, ErrorModel} = require('../model/resModel')
const { set } = require('../db/redis')

//获取cookie的过期时间
const getCookieExpires = ()=>{
    const d = new Date()
    d.setTime(d.getTime() + (24 * 60 * 60 * 1000))
    return d.toGMTString()
    
}

const handleUserRouter = (req,res) =>{
    const method = req.method
    const url = req.url
    const path = url.split('?')[0]

    //登陆
    if(method === 'POST' && path==='/api/user/login'){
        const { username, password } =req.body
        // const { username, password } = req.query

        const result = login(username, password)
        // result   Promise { <pending> }
        return result.then(data => {
            // data: RowDataPacket { username: 'lisi', realname: '李四2' }
            // data.username : lisi
            if(data.username){
                //设置 session
                req.session.username = data.username
                req.session.realname = data.realname
                //同步到redis
                set(req.sessionId, req.session)
                // console.log('req.session is ',req.session)

                return new SuccessModel()
            }
            return new ErrorModel('登陆失败')
        })
    }

    // //登录验证的测试
    // if(method === 'GET' && req.path === '/api/user/login-test'){
    //     if(req.session.username){
    //         return Promise.resolve(
    //             new SuccessModel({
    //              session: req.session
    //         })
    //         )

    //     }
    //     return Promise.resolve(
    //          new ErrorModel('尚未登录')

    //     )
    // } 
}

module.exports = handleUserRouter 
  

